﻿using CommonEntity.BatteryEntity;
using CommonEntity.CPUEntity;
using CommonEntity.PackageEntity;
using CommonEntity.ShellEntity;
using CommonHelper;
using DotNetCore.CAP;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using PackageAPI.Context;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace PackageAPI.Controllers
{
    /// <summary>
    /// Package相关信息服务接口
    /// </summary>
    [Route("[controller]")]
    [ApiController]
    public class PackageController : ControllerBase
    {
        private readonly ILogger<PackageController> _logger;
        private readonly IConfiguration _configuration;
        private readonly ICapPublisher _capBus;
        private readonly PackageContext _context;
        private readonly IDatabase _redis;

        public PackageController(ILogger<PackageController> logger, IConfiguration configuration, ICapPublisher capPublisher, PackageContext context, RedisHelper client)
        {
            _logger = logger;
            _configuration = configuration;
            _capBus = capPublisher;
            _context = context;
            _redis = client.GetDatabase();
        }

        /// <summary>
        /// 获取Package服务IP和端口
        /// </summary>
        /// <returns></returns>
        [Route("PackageServer")]
        [HttpGet]
        public IActionResult GetPackageServer()
        {
            return Ok($"【Package服务】{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}--{Request.HttpContext.Connection.LocalIpAddress}:{_configuration["ConsulSetting:ServicePort"]}");
        }

        /// <summary>
        /// 组装手机
        /// </summary>
        /// <returns></returns>
        [Route("Create")]
        [HttpGet]
        public async Task<IActionResult> CreatePhone()
        {
            try
            {
                string[] Phone = new string[] { "华为手机", "小米手机", "苹果手机" };
                var curCPUID = new Random(Guid.NewGuid().GetHashCode()).Next(1, 4);
                var curShellID = new Random(Guid.NewGuid().GetHashCode()).Next(1, 3);
                var curBatteryID = new Random(Guid.NewGuid().GetHashCode()).Next(1, 4);
                //从缓存取数据 只有数量大于0的时候才允许组装
                List<CPUInfo> cpuInfos = new List<CPUInfo>();
                _redis.SetMembers("CPUInfos").ToList().ForEach(a => cpuInfos.Add(JsonConvert.DeserializeObject<CPUInfo>(a)));
                List<ShellInfo> shellInfos = new List<ShellInfo>();
                _redis.SetMembers("ShellInfos").ToList().ForEach(a => shellInfos.Add(JsonConvert.DeserializeObject<ShellInfo>(a)));
                List<BatteryInfo> batteryInfos = new List<BatteryInfo>();
                _redis.SetMembers("BatteryInfos").ToList().ForEach(a => batteryInfos.Add(JsonConvert.DeserializeObject<BatteryInfo>(a)));
                if (cpuInfos.Where(q => q.ID == curCPUID).Select(a => a.TotalCount).FirstOrDefault() == 0 ||
                    shellInfos.Where(q => q.ID == curShellID).Select(a => a.TotalCount).FirstOrDefault() == 0 ||
                    batteryInfos.Where(q => q.ID == curBatteryID).Select(a => a.TotalCount).FirstOrDefault() == 0)
                {
                    return BadRequest("请检查CPU、Battery、Shell是否还有余量！");
                }

                using (var trans = _context.Database.BeginTransaction(_capBus, autoCommit: true))
                {
                    PackageInfo packageInfo = new PackageInfo();
                    packageInfo.PhoneName = Phone[new Random(Guid.NewGuid().GetHashCode()).Next(0, 2)];
                    packageInfo.CPUID = curCPUID;
                    packageInfo.ShellID = curShellID;
                    packageInfo.BatteryID = curBatteryID;
                    packageInfo.CreateTime = DateTime.Now;
                    _context.PackageInfos.Add(packageInfo);

                    var r = await _context.SaveChangesAsync() > 0;
                    if (r)
                    {
                        //发布组装事件
                        await _capBus.PublishAsync("PackageAPI.CreatePhone", 
                            new PackageInfo() 
                            { 
                                CPUID= packageInfo.CPUID,
                                ShellID= packageInfo.ShellID,
                                BatteryID=packageInfo.BatteryID
                            });

                        //更新redis
                        var batchExe = _redis.CreateBatch();
                        _redis.KeyDelete("PackageInfos");
                        _context.PackageInfos.ToList().ForEach(a => batchExe.SetAddAsync("PackageInfos", JsonConvert.SerializeObject(a)));
                        batchExe.Execute();

                        return Ok(packageInfo);
                    }
                    return BadRequest();
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex);
            }
        }


    }
}
